package com.aaa.security.aspect;

import com.aaa.security.util.IPUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.aaa.entity.OperLog;
import com.aaa.security.annotation.MyLog;
import com.aaa.security.dao.AOPOperLogDao;
import com.aaa.security.util.WebUtils;
import com.aaa.util.JwtUtil;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

/**
 * @author ：1452863884@qq.com rcg
 * @date ：Created in 2023/2/28 14:13
 * @description：日志的切面类
 * @modified By：
 * @version:
 */
@Component
@Aspect
public class MyLogAspect {

    private static final Logger LOGGER = LoggerFactory.getLogger(MyLogAspect.class);
    //开始时间
    private Date operTime;
    //访问的方法全路径
    private String method;
    //获取方法参数类型
    private String methodParType;
    //获取方法参数名
    private String methodParName;
    //获取方法参数值
    private String methodParvalue;
    //获取方法返回值
    private String methodReturn;
    //用户名
    private String userName;

    //定义一个共有的名字
    private static String presentName = "";

    private static Class<?> clazz = null;


    /**
     * 定义切点方法
     */
    @Pointcut(value = "@annotation(com.aaa.security.annotation.MyLog)")
    public void pointcut() {

    }

    @Autowired
    private AOPOperLogDao operLogDao;

    //前置通知,主要是获取开始时间，执行的类是哪一个，执行的是哪一个方法
    @Before("pointcut()") //需要拦截的路径
    public void doBefore(JoinPoint jp) throws ClassNotFoundException, NoSuchMethodException {

        //当前时间就是开始访问的时间

        operTime = new Date();
        //具体要访问的类
        clazz = jp.getTarget().getClass();
        //获取访问的方法的名称
        String methodName = jp.getSignature().getName();
        //方法全路径
        method = jp.getTarget().getClass().getName() + "." + methodName;
        System.out.println("method = " + method);
        Object[] args = jp.getArgs();//获取访问的方法的参数值
        LOGGER.info("参数值:" + Arrays.toString(args));
        methodParvalue = Arrays.toString(args);

        Class[] paramTypes = null;  //获取参数类型
        Method[] methods = clazz.getMethods();

        for (int i = 0; i < methods.length; i++) {
            if (methodName.equals(methods[i].getName())) {//和传入方法名匹配
                Class[] params = methods[i].getParameterTypes();
                paramTypes = new Class[params.length];
                for (int j = 0; j < params.length; j++) {
                    paramTypes[j] = Class.forName(params[j].getName());
                }
                break;
            }
        }
        LOGGER.info("参数的类型:" + Arrays.toString(paramTypes));
        methodParType = Arrays.toString(paramTypes);


        //spring中的 类  用于获取方法的参数名称
        LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
        //获取方法的 全部的参数名称
        String[] params = u.getParameterNames(clazz.getMethod(methodName, paramTypes));
        LOGGER.info("参数名称:" + Arrays.toString(params));
        methodParName = Arrays.toString(params);

        //获方法的返回值类型
        Type t = clazz.getMethod(methodName, paramTypes).getAnnotatedReturnType().getType();
        LOGGER.info("方法的返回值类型:" + t);
        methodReturn = t.toString();

        LOGGER.info("执行前置通知了");



    }

    //后置通知  如果出现异常就不执行
    @After("pointcut()")
    public void doAfter(JoinPoint jp) throws Exception {
        String url = "";
        //在springmvc任意唯一获取request对象。
        HttpServletRequest request = WebUtils.getRequest();

        String ipAddr = IPUtils.getIpAddr(request);
        //得到UserAgent对象
        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        //获得浏览器信息

        Browser browser = userAgent.getBrowser();
        String browsers = browser + "";
        System.out.println("浏览器    " + browsers);
        //获得操作系统信息
        OperatingSystem os = userAgent.getOperatingSystem();
        String oss = os + "";
        System.out.println("os  " + oss);
        //获得ip信息
        String ip = "";
        try {
            //ip 地址
            ip = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        OperLog operLog=new OperLog();


        String requestURI = request.getRequestURI();


        //获取方法对象。
        MethodSignature methodSignatur= (MethodSignature) jp.getSignature();
        Method method = methodSignatur.getMethod();
        String methodName = method.getName();
        //获取方法上
        MyLog annotation = method.getAnnotation(MyLog.class);

        String token = request.getHeader("token");

        if (StringUtils.isNotBlank(token)){

            //解析token
            Map<String, Object> map = JwtUtil.getTokenChaim(token);
            userName= map.get("username").toString();
        }
        //调用mapper完成插入操作
        // 使用StringUtils工具类，判断不为null也不是空，
        if(StringUtils.isNotBlank(ipAddr)
                && StringUtils.isNotBlank(browsers)
                && StringUtils.isNotBlank(oss)){


            operLog.setOperTime(operTime);
            operLog.setOperIp(ipAddr);
            operLog.setOperLocation("内网ip");
            operLog.setMethod(method.toString());
            operLog.setOperUrl(requestURI);
            operLog.setOperParam(methodParType);

            operLog.setTitle(annotation.title());
            operLog.setBusinessType(annotation.businessType());

            operLog.setOperName(userName);
            operLog.setDeptName("研发部门");

            int insert = operLogDao.insert(operLog);

        }

        LOGGER.info("执行最终通知");
    }


}